import React, { useState, createContext, useRef, useContext } from "react";
import { Button, Modal, Form } from "react-bootstrap";
import InputBox from "./InputBox";

/**
 * @type {React.Context<(title: string, prompt: string, validator?: import("./InputBox").ValidatorFunction => Promise<string>}
 */
const InputBoxContext = createContext({});

function InputBoxProvider(props) {
    let [showModal, setShowModal] = useState(false);
    let [title, setTitle] = useState('');
    let [prompt, setPrompt] = useState('');
    let [inputValue, setInputValue] = useState('');
    let [validator, setValidator] = useState();
    let resolveRef = useRef(null);

    const handleResult = (result) => {
        resolveRef.current(result);
        setShowModal(false);
    };

    const show = (title, prompt, validator) => {
        setTitle(title);
        setPrompt(prompt);
        setShowModal(true);
        setValidator(() => validator);

        return new Promise((resolve, reject) => {
            resolveRef.current = resolve;
        });
    };
    console.log(validator);

    return (
        <InputBoxContext.Provider value={show}>
            <InputBox
                title={title}
                prompt={prompt}
                inputValue={inputValue}
                setInputValue={setInputValue}
                showModal={showModal}
                onResult={handleResult}
                validator={validator}
            />
            {props.children}
        </InputBoxContext.Provider>
    );
}

/** 
 * 以 Context 方式使用 InputBox。
 * 
 */
function useInputBox() {
    return useContext(InputBoxContext);
}

export default useInputBox;
export { InputBoxProvider, InputBoxContext };